<?php

/***************************************************************\
* FILE:		/sys/login.inc
* SECTION:	core - session
* FUNCTION:	initiate and maintain session variables
* USES:		cookie login info: $_COOKIE[]
*		form login info: $_POST[]
* INCLUDES:	none
* PRODUCES:	$_SESSION['user_id']
*		$_SESSION['user_groups']
*		$_SESSION['user_ipstring']
*		$_SESSION['member']
* LAUNCHES:	none
\***************************************************************/

/**
 * initiate session variables if login info provided
 */
function login($justregistered = 0) {

	if ($_SESSION['user_id'])
		return;

	global $CONFIG;

	if (!$justregistered) {
		processCookieInfo();

		// 1.b. process login information
		if (!checkForLoginData)
			return; 

		$login = $_POST['login'];
		$pwd = md5($CONFIG['pwd_prefix'].$_POST['password'].$CONFIG['pwd_suffix']);

		$sql = db_query_select(array(array('pwd', 'user_id', 'title')), array('MEMBER'), "MEMBER.nick LIKE ".db_sqlize($_POST['login']));
		
		// 2. check credentials
		$sqlresult = db_do_query($sql);
	
		if (db_num_rows($sqlresult) != 1) {
			if ($_POST['login'] != "")
				login_catch("account '{$_POST['login']}' does not exist");
			else
				login_catch("account #$uid does not exist");
			return;
		}
		
		$result = db_fetch_array($sqlresult);
		
		if (isset($_POST['login']) and ($pwd != $result['pwd'])) {
			login_catch("fout wachtwoord voor account '{$_POST['login']}'");
			return;
		}

		if ($result['title'] == "nog inactief") {
			login_catch("account '{$_POST['login']}' is nog niet geactiveerd. Dit doe je door de link te volgen in de welkomstmail die je kreeg na je registratie.");
			return;
		}

		$user_id = $result['user_id'];
	
		// 4. update counter
		$ipstring = $_SERVER["REMOTE_ADDR"]." - ".$_SERVER["HTTP_X_FORWARDED_FOR"];
		$sql = db_query_select(array(array("*")), array('COUNTER'), "user_id = $user_id AND ipstring = ".db_sqlize($ipstring));
		$sqlresult = db_do_query($sql);
		
		if (db_num_rows($sqlresult)) {
			$sql = db_query_update(array('logins'), array('logins+1'), "COUNTER", "user_id = $user_id AND ipstring = ".db_sqlize($ipstring));
			db_do_query($sql);
		} else {
			$sql = db_query_insert(array('user_id', 'ipstring', 'logins'), array($user_id, db_sqlize($ipstring), 1), "COUNTER");
			db_do_query($sql);
		}
	} else
		$user_id = $justregistered;
	
	// 5. set session variables
	session_register("member", "user_id", "user_groups", "user_ipstring", "country");
	$sql = db_query_select(array(array('*')), array("MEMBER"), "MEMBER.user_id = $user_id");
	$sqlresult = db_do_query($sql);
	$member = db_fetch_array($sqlresult);
	$_SESSION['member'] = $member;
	$_SESSION['user_id'] = $user_id;
	$_SESSION['user_ipstring'] = $ipstring;

	// TODO register preferences in $CONFIG

	$sql = db_query_select(array(array("usergroup_id")), array("IN_USERGROUP"), "user_id = $user_id");
	$sqlresult = db_do_query($sql);
	$groups = array();
	while ($result = db_fetch_array($sqlresult))
		array_push($groups, $result['usergroup_id']);
	$_SESSION['user_groups'] = $groups;

	// 3. update profiles
	$sql = db_query_update(array('member_since', 'last_visit'), array('member_since', 'NOW(14)'), 'MEMBER', "user_id = $user_id");
	db_do_query($sql);
		
	// 6. update cookie
	if ($member['pref_logon_time'])
		setcookie($CONFIG['cookie_name'], "{$user_id}@@{$pwd}", time()+86400*$member['pref_logon_time'], '/');
		
	// derive country
	include_once('sys/regionfunctions.inc');
	$sqlres = db_do_query(db_query_select(array(array('*')), array('IN_REGION'), "user_id = $user_id"));
	if (db_num_rows($sqlres))
		$r = db_fetch_array($sqlres);
	if ($r['region_id']) {
		$path = region_get_region_tree($r['region_id']);
		$c_id = $path[count($path)-1]['region_id'];
		switch($c_id) {
			case 1: $_SESSION['country'] = "BE"; break;
			case 2: $_SESSION['country'] = "NL"; break;
		}
	}
	
}

function processCookieInfo() {
	// 1.a. process cookie information
	if ($_COOKIE[$CONFIG['cookie_name']] != "") {
	
		$cookie = explode("@@", $_COOKIE[$CONFIG['cookie_name']]);
	
		if (count($cookie) != 2) {
			login_catch("cookie beschadigd.");
			setcookie($CONFIG['cookie_name'], "", time() - 3600);
			return;
		}
	
		list($uid, $pwd) = $cookie;

		// empty cookie means shit
		if ($uid == "")
			login_catch("empty cookie, trying harder");		

		$sql = db_query_select(array(array('pwd', 'user_id', 'title')), array('MEMBER'), "MEMBER.user_id = $uid");
	}
}

function checkForLoginData() {
	if (!isset($_POST['login'])) {
		return false;
	}

	if (!isset($_POST['password'])) {
		login_catch("no password supplied with login '{$_POST['login']}'");
		return false;
	}
	return true;
}

/**
 * destroy session info
 */
function logout() {
	global $CONFIG;
	session_unset('user_id', 'user_groups', 'user_ipstring', 'member');
	session_destroy();
	setcookie($CONFIG['cookie_name'], "", time()+8640000, '/');
}

/**
 * catch login errors
 */
function login_catch($error) {
	endpage($error);
}

?>
